using UnityEngine;

public class ArrowController : MonoBehaviour
{
    private Rigidbody2D rb;
    private Collider2D coll;
    private ParticleSystem ps;
    [SerializeField] private int damage = 1;
    [SerializeField] private float xVelocity;
    private bool isFlipped;
    private bool canMove = true;
    private CharacterStats playerStats;
    private CharacterStats enemyStats;

    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        coll = GetComponent<Collider2D>();
        ps = GetComponentInChildren<ParticleSystem>();
    }

    void Update()
    {
        if (canMove)
        {
            rb.velocity = new Vector2(xVelocity, rb.velocity.y);
        }
    }

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.layer == LayerMask.NameToLayer("Ground"))
        {
            StuckInto();
        }
        if (isFlipped && collision.TryGetComponent(out Enemy enemy))
        {
            playerStats.DoDamage(enemy.Stats);
        }
        else if (!isFlipped && collision.TryGetComponent(out Player player))
        {
            enemyStats.DoDamage(player.Stats);
        }
        StuckInto();
        transform.parent = collision.transform;
    }

    public void Setup(CharacterStats enemyStats, CharacterStats playerStats, int facingDirection, float speed, int damage)
    {
        if (facingDirection == -1)
        {
            transform.Rotate(0, 180, 0);
        }
        xVelocity = speed;
        this.damage = damage;
        this.enemyStats = enemyStats;
        this.playerStats = playerStats;
    }

    private void StuckInto()
    {
        canMove = false;
        coll.enabled = false;
        ps.Stop();
        rb.constraints = RigidbodyConstraints2D.FreezeAll;
        rb.isKinematic = true;
        Destroy(gameObject, Random.Range(5, 7));
    }

    public void Flip()
    {
        if (isFlipped) return;
        xVelocity = -xVelocity;
        isFlipped = true;
        transform.Rotate(0, 180, 0);
    }
}
